Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Course Overview
Basics of Tree
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Level Order Traversal Pattern (easy)
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Tree Depth Pattern (easy)
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Sum of Nodes with Even-Valued Grandparent

Problem Statement

Given the root of a binary tree, return the total sum of the values of all nodes that have a grandparent with an even number. If no such nodes exist, return 0.

A grandparent of a node is defined as the parent of its parent, if both exist.

Examples

Example 1:

  • Input: root = [4, 2, 6, 3, 5, null, 8]
  • Expected Output: 16
Image
  • Justification: Node values 3, 5, and 8 have 4 as their grandparent. Since 4 is even, their sum is 3 + 5 + 8 = 16.

Example 2:

  • Input: root = [2, 3, 8, null, 5, 7, null, 2, 3, 4, 5]
  • Expected Output: 21
Image
  • Justification: Node value 5 and 7 has 2 as its grandparent, and Node value 4 and 5 has grandparent 8. So, sum = 5 + 7 + 4 + 5 = 21.

Example 3:

  • Input: root = [5, 9, 12, null, null, 8, 4]
  • Expected Output: 0
Image
  • Justification: Node values 8 and 4 has 5 as its grandparent. However, since 5 is not even, they are not included. So, the answer is 0.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 1 <= Node.val <= 100

Solution

The algorithm for finding the sum of nodes with even-valued grandparents begins by checking if the root is null, returning 0 if true. We then initialize a queue for BFS traversal, starting with the root node, and a variable sum to keep track of the result. For each node, if its value is even, we check its left and right children for grandchildren, adding their values to the sum if they exist. All non-null children are added to the queue to continue the BFS traversal. This process repeats until all nodes are processed, and the final sum is returned.

Step-by-Step Algorithm

Step 1: Check if the tree is empty:

  • If the root is null, return 0. This handles the case where the binary tree is empty.

Step 2: Initialize the sum variable:

  • A variable sum is initialized to 0. This will keep track of the total sum of the node values that meet the condition of having an even-valued grandparent.

Step 3: Initialize a queue for level order traversal (BFS):

  • A Queue is used to perform BFS traversal starting from the root. The root node is added to the queue.

Step 4: Perform BFS traversal:

  • While the queue is not empty, perform the following steps for each node:

    1. Step 4.1: Remove the front node from the queue:

      • Use queue.poll() to remove the current node for processing.
    2. Step 4.2: Check if the current node's value is even:

      • If current.val % 2 == 0, it means the current node has an even value.
      • If the current node is even-valued, we will check for its grandchildren.
    3. Step 4.3: Add the values of the grandchildren (if they exist):

      • Left grandchild check:
        • If the left child of the current node exists (current.left != null), then check for its children (i.e., grandchildren of the current node).
        • If the left grandchild exists (current.left.left != null), add its value to sum.
        • If the right grandchild exists (current.left.right != null), add its value to sum.
      • Right grandchild check:
        • If the right child of the current node exists (current.right != null), then check for its children.
        • If the left grandchild exists (current.right.left != null), add its value to sum.
        • If the right grandchild exists (current.right.right != null), add its value to sum.
    4. Step 4.4: Add the children of the current node to the queue for further processing:

      • If the left child exists (current.left != null), add it to the queue.
      • If the right child exists (current.right != null), add it to the queue.

Step 5: Return the total sum:

  • After processing all nodes in the tree, return the value of sum, which represents the sum of all nodes with even-valued grandparents.

Algorithm Walkthrough

Image

Step 1: Processing the Root Node (Value 4)

  • We begin at the root node with the value 4. The queue initially contains only the root node: Queue = [4].

  • The variable sum is initialized to 0.

  • Since 4 is an even-valued node, we now check the values of its grandchildren:

    • Exploring children of the left child (Node 2):
      • The left child of 4 is 2, which has two children: 3 and 5. Both are the grandchildren of node 4.
      • We add the values of both 3 and 5 to sum.
      • Updated sum = 0 + 3 + 5 = 8.
    • Exploring children of the right child (Node 6):
      • The right child of 4 is 6. It has one child: 8, which is also a grandchild of node 4.
      • We add the value of 8 to sum.
      • Updated sum = 8 + 8 = 16.
  • After processing the grandchildren of 4, we add its left child (2) and right child (6) to the queue for further processing.

    • Queue = [2, 6].

Step 2: Processing Node 2

  • The next node in the queue is 2. We remove it from the queue: Queue = [6].

  • Since 2 is an even-valued node, we now check the values of its grandchildren:

    • Exploring children of the left child (Node 3):
      • The left child of 2 is 3. Node 3 has no children, so there are no grandchildren to add to sum.
    • Exploring children of the right child (Node 5):
      • The right child of 2 is 5. Node 5 also has no children, so there are no grandchildren to add to sum.
  • Since there are no grandchildren for node 2, the sum remains unchanged at 16.

  • We then add its children (3 and 5) to the queue for further processing.

    • Queue = [6, 3, 5].

Step 3: Processing Node 6

  • The next node in the queue is 6. We remove it from the queue: Queue = [3, 5].

  • Since 6 is an even-valued node, we now check the values of its grandchildren:

    • Exploring children of the right child (Node 8):
      • The right child of 6 is 8. Node 8 has no children, so there are no grandchildren to add to sum.
  • Since there are no grandchildren for node 6 that haven’t already been processed, the sum remains unchanged at 16.

  • We then add its right child (8) to the queue for further processing.

    • Queue = [3, 5, 8].

Step 4: Processing Node 3

  • The next node in the queue is 3. We remove it from the queue: Queue = [5, 8].

  • Since 3 is an odd-valued node, we do not process its grandchildren.

  • Node 3 has no children, so no further nodes are added to the queue.

Step 5: Processing Node 5

  • The next node in the queue is 5. We remove it from the queue: Queue = [8].

  • Since 5 is an odd-valued node, we do not process its grandchildren.

  • Node 5 has no children, so no further nodes are added to the queue.

Step 6: Processing Node 8

  • The last node in the queue is 8. We remove it from the queue: Queue = [].

  • Since 8 is an even-valued node, we would normally check its grandchildren. However, node 8 has no children, so no further nodes are added to the queue.

Final Step: End of BFS Traversal

  • The queue is now empty, so the BFS traversal is complete.
  • The total sum of all grandchildren of even-valued nodes is 16.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where n is the number of nodes in the binary tree. This is because we traverse each node exactly once using a level order traversal, checking each node to see if it has an even-valued grandparent and adding the values of its grandchildren if applicable.

Space Complexity

The space complexity is , where m is the maximum number of nodes at any level of the binary tree. In the worst case, this can be proportional to the width of the tree. If the tree is a complete binary tree, this will be . This space is needed for the queue used in the level order traversal.

Sum of Nodes with Even-Valued Grandparent (medium)
All Nodes Distance K in Binary Tree (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity